package com.rocker.graduation.util;

import java.awt.Color;
import java.util.Random;

import com.github.bingoohuang.patchca.background.MyCustomBackgroundFactory;
import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DiffuseRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DoubleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.MarbleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.WobbleRippleFilterFactory;
import com.github.bingoohuang.patchca.word.RandomWordFactory;

public class CaptchaUtils {
	private static  ConfigurableCaptchaService captchaService = new ConfigurableCaptchaService();
	
	private static Random random = new Random();
	
	static{
		captchaService.setColorFactory(new ColorFactory() {
			
			@Override
			public Color getColor(int x) {
				int[] c = new int[3];
				int i = random.nextInt(c.length);
				for (int j = 0; j < c.length; j++) {
					if (j == i) {
						c[j] = random.nextInt(71);
					}else {
						c[j] = random.nextInt(256);
					}
				}
				return new Color(c[0], c[1], c[2]);
			}
		});
		RandomWordFactory wordFactory = new RandomWordFactory();
		wordFactory.setCharacters("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		wordFactory.setMaxLength(4);
		wordFactory.setMinLength(4);
		captchaService.setWordFactory(wordFactory);
	}
	
	public static ConfigurableCaptchaService getCaptcha(){
		int i = random.nextInt(5);
		switch (i) {
		case 0:
			captchaService.setFilterFactory(new CurvesRippleFilterFactory(captchaService.getColorFactory()));
			break;
		case 1:
			captchaService.setFilterFactory(new MarbleRippleFilterFactory());
			break;
		case 2:
			captchaService.setFilterFactory(new DoubleRippleFilterFactory());
			break;
		case 3:
			captchaService.setFilterFactory(new WobbleRippleFilterFactory());
			break;
		case 4:
			captchaService.setFilterFactory(new DiffuseRippleFilterFactory());
			break;
		default:
			break;
		}
		captchaService.setBackgroundFactory(new MyCustomBackgroundFactory());
		return captchaService;
	}
}
